<?php

namespace app\api\service\weixin;

use app\admin\model\Groupdetail;
use app\admin\model\Groupproduct;
use app\admin\model\Member;
use app\admin\model\Orderitem;
use app\admin\model\Rechargerecord;
use app\admin\model\Salesvolume;
use app\api\controller\Integralproduct;
use app\api\service\Detailed;
use app\common\DictConstant;
use think\Db;
use think\Exception;
use app\common\model\Order as OrderModel;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

/**
 * 处理微信支付回调
 * Class WxNotify
 * @package app\api\service
 */
class OrderNotify extends \WxPayNotify
{

    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>
    public function NotifyProcess($data, &$msg){
        if($data['result_code'] == 'SUCCESS'){
            //支付成功后，把订单信息加入到Rabbitmq中，防止回调业务中有异常导致支付状态异常，做最终一致性校验
            $orderId = $data['out_trade_no'];
            $paytime = self::timeFormat($data['time_end']);
            Db::startTrans();
            try
            {
                $order = \app\common\model\Order::where('id','=',$orderId)->lock(true)->find();
                if($order->link_type == 1){ //普通订单
                    if($order->status == 1){
                        //写入微信支付单号
                        $transaction_id = $data['transaction_id'];
                        \app\common\model\Order::where('id',$orderId)->update(['transaction_id'=>$transaction_id,'pay_date'=>$paytime,'pay_method'=>1]);
                        //更新订单状态
                        $this->updateOrderStatus($order->id,$order->link_type);
                        //更新订单占用减库存
                        $this->reduceStock($order->id);
                        //更新销量
                        $this->updatesalesvolume($order->id);
                    }
                }else{
                    //拼团订单
                    if($order->status == 1){
                        $transaction_id = $data['transaction_id'];
                        \app\common\model\Order::where('id',$orderId)->update(['transaction_id'=>$transaction_id,'pay_date'=>$paytime,'pay_method'=>1]);
                        $this->updateOrderStatus($order->id,$order->link_type);
                        //更新订单占用减库存
                        $this->reduceStock($order->id);
                        $this->updateUserGroupStatus($order->id);
                    }
                }
                Db::commit();
                //改变用户首单立减状态
                if($order->first_order_reduce >0){
                    Member::where('id',$order->member_id)->update(['isfirst_order_reduce'=>1]);
                }
                //会员消费送积分
                Integralproduct::consumptiongiveintegral($order->member_id,$order->total,$order->id,2);
                return true;
            }catch (Exception $ex){
                Db::rollback();
                Log::record($ex);
                return false;
            }
        }else{
            return true;
        }
    }


    private function reduceStock($orderId){
        $Orderitem = Orderitem::where('order_id',$orderId)->field('product_id,count')->select();
        foreach ($Orderitem as $v){
            db('stock')->where('product_id',$v['product_id'])->setDec('order_stock',$v['count']);
        }
    }

    private function updateOrderStatus($orderID,$linkType){
        if($linkType == 1){
            $status = DictConstant::OrderPendingDelivery;
        }else{
            $status = DictConstant::Order_GroupIng;
        }

        OrderModel::where('id','=',$orderID)->update(['status'=>$status]);
        Orderitem::where('order_id',$orderID)->update(['old_status'=>$status]);

    }

    public static function updatesalesvolume($orderId){
        $item = db('order_item')->where('order_id',$orderId)->field('product_id,count')->select();
        if($item){
            $newarr = [];
            foreach ($item as $v){
                $res = Salesvolume::where('product_id',$v['product_id'])->find();
                if($res){
                    $res->setInc('sales_num',$v['count']);
                }else{
                    array_push($newarr,['product_id'=>$v['product_id'],'sales_num'=>$v['count']]);
                }
            }
            if($newarr){
                $model = new Salesvolume();
                $model->saveAll($newarr);
            }
        }
    }

    private function updateUserGroupStatus($orderId){
        $Groupdetail = Groupdetail::where('order_id',$orderId)->find();  //groupproduct
        $Groupproduct = Groupproduct::get($Groupdetail->group_id);
        $chentuannum = $Groupproduct->group_succ_count;
        $oktime = $Groupproduct->group_succ_time;
        if($Groupdetail->member_id == $Groupdetail->originator){
            $endDate = time()+$oktime;
        }else{
            $tuanzhang = Groupdetail::get($Groupdetail->unigroup_id);
            $endDate = $tuanzhang->end_date;
        }
        $goups = Groupdetail::where('unigroup_id',$Groupdetail->unigroupId)->lock(true)->count();
        if($chentuannum > $goups){
            $Groupdetail->end_date = $endDate;
            $Groupdetail->status = 1;
            $Groupdetail->is_pay = 1;
            $Groupdetail->save();
        }elseif ($chentuannum == $goups){
            $allgroups = Groupdetail::where('unigroup_id',$Groupdetail->unigroup_id)->select();
            $list = [];
            foreach ($allgroups as $v){
                array_push($list,['id'=>$v['id'],'status'=>2,'is_pay'=>1,'end_date'=>$endDate]);
            }
            (new Groupdetail())->saveAll($list);
            //把订单里所有该团的状态改为待发货
            $this->updateGroupOrderStatus($Groupdetail->unigroup_id);
            //发送小程序模板消息（先写入队列）

        }else{
            //todo

        }
    }

    private function updateGroupOrderStatus($unigroupId){
        $Groupdetail = Groupdetail::where('unigroup_id',$unigroupId)->select();
        $listorder = [];
        foreach ($Groupdetail as $v){
            $status = DictConstant::OrderPendingDelivery;
            array_push($listorder,['id'=>$v['order_id'],'status'=>$status]);
        }
        $order = new \app\common\model\Order();
        $order->saveAll($listorder);
        $Orderitem = new Orderitem();
        $list = [];
        foreach ($Groupdetail as $value){
            $status = DictConstant::OrderPendingDelivery;
            array_push($list,$value['order_id']);
        }
        $Orderitem->where('order_id','in',$list)->update(['old_status'=>$status]);
    }


    public static function timeFormat($time){
        $paytime = substr($time,0,4).'-';
        $paytime .= substr($time,4,2).'-';
        $paytime .= substr($time,6,2);
        $paytime .= ' ';
        $paytime .= substr($time,8,2).':';
        $paytime .= substr($time,10,2).':';
        $paytime .= substr($time,12,2);
        $paytime = date('Y-m-d H:i:s',strtotime($paytime));
        return $paytime;
    }

}